package com.lsq.test;

import com.lsq.spring.BeanPostProcessor;
import com.lsq.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author lsq
 * @description AOP原理
 * @date 2023/9/5
 */
@Component
public class LsqBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if (beanName.equals("userService")) {
            System.out.println("初始化前");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("初始化后");
        //判断是否进行aop
        if (beanName.equals("userService")) {
            Object proxyBean = Proxy.newProxyInstance(LsqBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("代理逻辑"); //找切点
                    return method.invoke(bean,args);
                }
            });
            return proxyBean;
        }


        return bean;
    }
}
